/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.web.action.debt;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.common.model.Student;
import ar.uba.fi.posgrado.common.util.CommonUtils;
import ar.uba.fi.posgrado.economy.model.Benefit;
import ar.uba.fi.posgrado.economy.model.Customer;
import ar.uba.fi.posgrado.economy.model.Debt;
import ar.uba.fi.posgrado.economy.model.Discount;
import ar.uba.fi.posgrado.economy.service.DebtService;
import ar.uba.fi.posgrado.economy.web.form.debt.DebtForm;

/**
 * Action que muestra una deuda para la visualizacion basicamente.<br>
 * 
 * @author nicolas.gonzalez
 * @see Action
 */
public class ViewDebtAction extends Action {

	/** Logger */
	private static Logger logger = Logger.getLogger(ViewDebtAction.class);
	
    private DebtService debtService;

    // IoC
    public void setDebtService(DebtService debtService) {
        this.debtService = debtService;
    }


	/**
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @SuppressWarnings("unchecked")
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("Por mostrar pantalla de modificacion de deuda ...");
        }
        DebtForm form = (DebtForm)actionForm;
        Long debtId = form.getId();
        Debt debt = this.debtService.getById(debtId);
        Student student = debt.getStudent();
        Customer customer = debt.getCustomer();
        Course course = debt.getCourse();
        
        Set<Discount> discounts = debt.getDiscounts();
        Set<Benefit> benefits = debt.getBenefits();
        
        form.setDiscountValues(this.calculateDiscount(discounts, "value"));
        form.setDiscountPerc(this.calculateDiscount(discounts, "percentage"));
        form.setBenefitValues(this.calculateBenefit(benefits, "value"));
        form.setBenefitPerc(this.calculateBenefit(benefits, "percentage"));
        // Tipo de concepto de la deuda.
        form.setDebtTypeSelected(debt.getDebtType().getDescription());
        // Datos del usuario
        form.setStudentId(student.getId());
        form.setStudentSurname(student.getSurnamePlusName());
        // Datos del cliente
        form.setCustomerId(customer.getId());
    	form.setCorporateName(customer.getCorporateName());
    	// Curso
    	form.setCourseSelected(course.getName());
    	
        // Fechas
        form.setValidityFrom(CommonUtils.formatDate(debt.getValidityFrom()));
        form.setExpiry(CommonUtils.formatDate(debt.getExpiry()));
        form.setBalance(debt.getBalance());
        form.setOriginalBalance(debt.getOriginalBalance());

        form.setDebtStatusStr(debt.getDebtStatus().toStringValue());
        
        logger.info("Mostrar pantalla de modificacion de deuda finalizado");
        return mapping.findForward("success");
    }

    
    /**
     * Calcula el acumulado de descuentos tanto por valor como
     * por porcentaje.<br>
     * 
     * @param discounts
     * @param valueOrPerc "value"|"percentage"
     * @return
     */
    private String calculateDiscount(Set<Discount> discounts, String valueOrPerc) {
        String response = "";

        Double aux = 0d;
        if (valueOrPerc.equals("value")) {
            for (Discount discount : discounts) {
                aux += discount.getValue();
            }
        }
        else {
            for (Discount discount : discounts) {
                aux += discount.getPercentage();
            }
        }
        response = String.valueOf(aux);
        
        return response;
    }

    /**
     * Calcula el acumulado de beneficios tanto por valor como
     * por porcentaje.<br>
     * 
     * @param benefits beneficios
     * @param valueOrPerc "value"|"percentage"
     * @return
     */
    private String calculateBenefit(Set<Benefit> benefits, String valueOrPerc) {
        String response = "";

        Double aux = 0d;
        if (valueOrPerc.equals("value")) {
            for (Benefit benefit: benefits) {
                aux += benefit.getValue();
            }
        }
        else {
            for (Benefit benefit: benefits) {
                aux += benefit.getPercentage();
            }
        }
        response = String.valueOf(aux);
        
        return response;
    }

}
